今天來試著在前端呼叫Rust執行的功能!
這是目前的畫面,今天要做的是在輸入框中寫字,點送出後將字顯示在中間。
要讓Rust和網頁交互,使用專門的套件會比較容易,這邊選擇的是Actix Web,這是一個Rust常用的Web框架,如果你有用過Python寫網頁,Rust和Actix Web的關係就像Python和Flask的關係類似。
一樣先建立Cargo的資料夾
cargo new battle_server
cd battle_server
建立完後會自動建立幾個檔案,找到其中的Cargo.toml並打開,這個文件類似JavaScript的package.json,在裡面寫下Rust需要用的套件後,執行時Cargo會自動下載,這次在裡面寫下Actix Web
[package]
name = "battle_server"
version = "0.1.0"
edition = "2021"
[dependencies]
actix-web = "4.3.1"
actix-cors = "0.6.4"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
前端的程式如下,送出輸入的字串給後端,並將返回值顯示在中間
    const sendCommand = async (command) => {
      try {
        const response = await fetch('http://localhost:8081/command', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ command }),
        });
        const data = await response.json();
        battleDescription.value = data.message;
      } catch (error) {
        console.error('Error sending command:', error);
        battleDescription.value = '發送指令時出錯,請稍後再試。';
      }
    };
後端的main.rs,這裡會監聽8081 port,收到傳來的字串後,返回一個"收到指令"+傳來的字串
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use actix_cors::Cors;
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct BattleCommand {
    command: String,
}
#[derive(Serialize)]
struct BattleResponse {
    message: String,
}
async fn handle_command(command: web::Json<BattleCommand>) -> impl Responder {
    let response = BattleResponse {
        message: format!("收到指令:{}", command.command),
    };
    HttpResponse::Ok().json(response)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        let cors = Cors::default()
            .allow_any_origin()
            .allow_any_method()
            .allow_any_header();
        App::new()
            .wrap(cors)
            .route("/command", web::post().to(handle_command))
    })
    .bind("127.0.0.1:8081")?
    .run()
    .await
}
最終成果: